package serial_ext

import (
	"go.bug.st/serial"
	"time"
)

const (
	PARITY_N     = 0 //无校验
	PARITY_O     = 1 //奇校验
	PARITY_E     = 2 //偶校验
	PARITY_MARK  = 3 //mark 校验
	PARITY_SPACE = 4 //space 校验
)

// 串口配置参数
type SerialParams struct {
	SerialName  string //串名称
	BaudRate    int    // The serial port bitrate (aka Baudrate)
	DataBits    byte   // Size of the character (must be 5, 6, 7 or 8)
	Parity      uint8  // Parity (see Parity type for more info)
	StopBits    uint8  // Stop bits (see StopBits type for more info)
	ReadTimeout time.Duration
	//InitialStatusBits *ModemOutputBits // Initial output modem bits status (if nil defaults to DTR=true and RTS=true)
}

func (params *SerialParams) SerialMode() *serial.Mode {

	mode := &serial.Mode{
		BaudRate: params.BaudRate,
		DataBits: int(params.DataBits),
	}

	switch params.StopBits {
	case 1:
		mode.StopBits = serial.OneStopBit
	case 2:
		mode.StopBits = serial.TwoStopBits
	case 15:
		mode.StopBits = serial.OnePointFiveStopBits
	default:
		mode.StopBits = serial.OneStopBit
	}

	switch params.Parity {
	case PARITY_N:
		mode.Parity = serial.NoParity
	case PARITY_E:
		mode.Parity = serial.EvenParity
	case PARITY_O:
		mode.Parity = serial.OddParity
	case PARITY_MARK:
		mode.Parity = serial.MarkParity
	case PARITY_SPACE:
		mode.Parity = serial.SpaceParity
	default:
		mode.Parity = serial.NoParity
	}

	return mode
}
